import api from './api';

export const userService = {
  // 用户登录
  login(email, password) {
    return api.post('/users/login', { email, password });
  },

  // 用户注册
  register(username, email, password) {
    return api.post('/users/register', { username, email, password });
  },

  // 获取用户信息
  async getMe() {
    try {
      const response = await api.get('/users/me');
      // console.log('userService.getMe: Full response object after api.get():', response);
      return response; // 直接返回response，而不是response.data
    } catch (error) {
      console.error('获取用户信息失败:', error);
      throw error;
    }
  },

  // 更新用户信息
  async updateProfile(userData) {
    try {
      const response = await api.put('/users/profile', userData);
      // console.log('userService.updateProfile: Full response object after api.put():', response);
      return response;
    } catch (error) {
      console.error('更新用户资料失败:', error);
      throw error;
    }
  },

  // 修改密码
  async changePassword(passwords) {
    try {
      const response = await api.put('/users/change-password', passwords);
      // console.log('userService.changePassword: Full response object after api.put():', response);
      return response;
    } catch (error) {
      console.error('修改密码失败:', error);
      throw error;
    }
  },

  async setDefaultCity(cityId) {
    try {
      const response = await api.post('/users/set-default-city', { cityId });
      return response.data;
    } catch (error) {
      console.error('设置默认城市失败:', error);
      throw error;
    }
  },

  // 添加收藏城市
  async addFavoriteCity(cityId) {
    try {
      const response = await api.post('/users/favorite-city', { cityId });
      return response.data;
    } catch (error) {
      console.error('添加收藏城市失败:', error);
      throw error;
    }
  },

  // 获取收藏城市列表
  async getFavoriteCities() {
    try {
      const response = await api.get('/users/favorite-cities');
      console.log('userService.getFavoriteCities: Data being returned from service:', response);
      return response;
    } catch (error) {
      console.error('获取收藏城市列表失败:', error);
      throw error;
    }
  },

  // 上传头像
  async uploadAvatar(formData) {
    try {
      const response = await api.post('/users/upload-avatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      console.log('userService.uploadAvatar: Full response object after api.post():', response);
      return response; // 直接返回响应
    } catch (error) {
      console.error('上传头像失败:', error);
      throw error;
    }
  },

  // 用户登出
  logout() {
    localStorage.removeItem('token'); // 移除存储的认证令牌
    // 可以添加其他需要清除的会话数据
    console.log('用户已登出，认证令牌已清除。');
  }
}; 